<template>
  <div class="user-permission-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>用户与权限管理</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="addUser">添加用户</el-button>
      </div>
      <div class="search-bar">
        <el-input placeholder="请输入用户名或姓名" v-model="searchQuery" class="input-with-select" @keyup.enter.native="fetchUsers">
          <el-button slot="append" icon="el-icon-search" @click="fetchUsers"></el-button>
        </el-input>
      </div>
      <el-table :data="users" style="width: 100%">
        <el-table-column prop="userId" label="用户ID" width="80"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="role" label="角色"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="contactInfo" label="联系方式"></el-table-column>
        <el-table-column prop="status" label="状态" width="100"></el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- Dialog for Add/Edit User -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <el-form :model="currentUser" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="currentUser.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" v-if="!currentUser.userId">
          <el-input type="password" v-model="currentUser.password"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="currentUser.role" placeholder="请选择角色">
            <el-option label="普通员工" value="普通员工"></el-option>
            <el-option label="档案管理员" value="档案管理员"></el-option>
            <el-option label="企业领导" value="企业领导"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="currentUser.name"></el-input>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="currentUser.contactInfo"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="currentUser.status" placeholder="请选择状态">
            <el-option label="启用" value="启用"></el-option>
            <el-option label="禁用" value="禁用"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import service from '@/utils/request';

export default {
  name: 'UserPermission',
  data() {
    return {
      users: [],
      dialogVisible: false,
      dialogTitle: '',
      currentUser: {
        userId: null,
        username: '',
        password: '',
        role: '',
        name: '',
        contactInfo: '',
        status: '启用'
      },
      searchQuery: ''
    };
  },
  created() {
    this.fetchUsers();
  },
  methods: {
    fetchUsers() {
      service.get('/user/list', {
        params: {
          search: this.searchQuery
        }
      })
        .then(res => {
          if (res.data.code === 200) {
            this.users = res.data.data;
          } else {
            this.$message.error(res.data.message || '获取用户列表失败');
          }
        })
        .catch(error => {
          console.error("Error fetching users:", error);
          this.$message.error('获取用户列表失败');
        });
    },
    addUser() {
      this.dialogTitle = '添加用户';
      this.currentUser = {
        userId: null,
        username: '',
        password: '',
        role: '',
        name: '',
        contactInfo: '',
        status: '启用'
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑用户';
      this.currentUser = { ...row }; // Copy user data to form
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        service.delete(`/user/delete/${row.userId}`)
        .then(res => {
          if (res.data.code === 200) {
            this.$message.success('删除成功');
            this.fetchUsers();
          } else {
            this.$message.error(res.data.message || '删除失败');
          }
        })
        .catch(error => {
          console.error("Delete failed:", error);
          this.$message.error('删除失败');
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    saveUser() {
      if (this.currentUser.userId) {
        service.put('/user/update', this.currentUser)
        .then(res => {
          if (res.data.code === 200) {
            this.$message.success('更新成功');
            this.dialogVisible = false;
            this.fetchUsers();
          } else {
            this.$message.error(res.data.message || '更新失败');
          }
        })
        .catch(error => {
          console.error("Update failed:", error);
          this.$message.error('更新失败');
        });
      } else {
        service.post('/user/add', this.currentUser)
        .then(res => {
          if (res.data.code === 200) {
            this.$message.success('添加成功');
            this.dialogVisible = false;
            this.fetchUsers();
          } else {
            this.$message.error(res.data.message || '添加失败');
          }
        })
        .catch(error => {
          console.error("Add failed:", error);
          this.$message.error('添加失败');
        });
      }
    }
  }
}
</script>

<style scoped>
.user-permission-container {
  padding: 20px;
}
.search-bar {
  margin-bottom: 20px;
  width: 50%; /* Adjust width as needed */
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
.box-card {
  width: 100%;
}
</style> 